package com.shicijiaoliu.service.impl;


import com.github.pagehelper.PageHelper;
import com.shicijiaoliu.pojo.User;
import com.shicijiaoliu.utils.MD5Utils;
import com.shicijiaoliu.mapper.Usermapper;
import com.shicijiaoliu.service.Userservice;
import com.shicijiaoliu.utils.ThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class UserserviceImpl implements Userservice {

    @Autowired
    private Usermapper usermapper;

    @Override
    public void update(User user) {
        user.setUpdateTime(LocalDateTime.now());
        usermapper.update(user);
    }

    @Override
    public User findByName(String username) {
        User u = usermapper.findByName(username);
        return u;
    }

    @Override
    public void register(String username, String password, String email, String phone, String nickname, String ruler) {
        //md5加密
        String md5string = MD5Utils.string2MD5(password);
        LocalDateTime createTime = LocalDateTime.now();
        LocalDateTime updateTime = LocalDateTime.now();
        //添加
        usermapper.add(username,md5string,email,phone,nickname,createTime,updateTime,ruler);
    }

    @Override
    public void updatepwd(String newpwd) {
        LocalDateTime now = LocalDateTime.now();
        newpwd = MD5Utils.string2MD5(newpwd);
        Map<String,Object> claims = ThreadLocalUtils.getThreadLocal();
        long id = (long)claims.get("id");
        usermapper.updatepwd(newpwd,now,id);
    }

    @Override
    public List<User> finduserBypage(int pagecount, int pagenumber, String username, String nickname) {
        int count = usermapper.getcount(null,null);
        int totalpage = (int) Math.ceil((double)count/pagenumber);
        if(pagecount>totalpage || pagecount <= 0){
            return null;
        }else{
            PageHelper.startPage(pagecount,pagenumber);
            return usermapper.finduserBypage(username,nickname);
        }
    }

    @Override
    public int getcount(String username, String nickname) {
        return usermapper.getcount(username,nickname);
    }

    @Override
    public User findByid(long id) {
        return usermapper.findByid(id);
    }

    @Override
    public void deluser(long id) {
        usermapper.deluser(id);
    }

    @Override
    public void updateimg(String src,long id) {
        usermapper.updateimg(src,LocalDateTime.now(),id);
    }

    @Override
    public void findpwd(String newpwd, String email) {
        LocalDateTime now = LocalDateTime.now();
        newpwd = MD5Utils.string2MD5(newpwd);
        long id = usermapper.findByEmail(email).getId();
        usermapper.updatepwd(newpwd,now,id);
    }


}
